// APP对象
const app = getApp()
// 工具函数
const util = require('../../utils/util')
// 更新用户信息
const updateMemInfo = require('../../config').updateMemInfo
// 上传图片接口url
const smallProgram = require('../../config').smallProgram

Page({
  data: {
    value: '',
    purposeData: [{
      name: '变美变瘦',
      flag: false
    }, {
      name: '健身',
      flag: false
    }],
    edit: false,
    sex: 0
  },
  // 页面加载
  onLoad: function (options) {
    // 编辑健身目的
    if (!util.isEmptyObject(options)) {
      var sex = this.data.sex
      // 判断options.sex是否为空
      if ((options.sex != 'null') && (options.sex != 'undefined')) {
        sex = options.sex
      }
      // 判断options.purpose是否为null
      if ((options.purpose != 'null') && (options.purpose != 'undefined')) {
        var purposeArr = options.purpose.split(";")
        var purposeData = this.data.purposeData
        var value = options.purpose

        purposeArr.forEach(function (item, index) {
          var length = purposeData.length
          var flag = false
          for (var i = 0; i < length; i++) {
            if (purposeData[i].name === item) {
              purposeData[i].flag = true
            }
          }
        })

        this.setData({
          purposeData: purposeData,
          value: value
        })
      }
      this.setData({
        sex: sex,
        edit: true
      })
      
    } else {
      // 设置性别
      this.setData({
        sex: app.updateUserInfo.sex
      })
    }
  },
  // 页面首次渲染完
  onReady: function () {
  },
  // 绑定数据
  tapInput: function(e){
    var value = e.detail.value
    this.setData({
      value: value
    })
  },
  // 选择健身目的
  tapSelect: function (e) {
    var index = e.currentTarget.dataset.index
    var purposeData = this.data.purposeData
    var value = this.data.value

    if (purposeData[index]['flag']){
      // 已经选中状态
      purposeData[index]['flag'] = false

      var selectJob = purposeData[index]['name']
      value = value.replace(';' + selectJob, '')
      value = value.replace(selectJob, '')
    } else {
      // 未选中状态
      purposeData[index]['flag'] = true
      if (value == '') {
        value = purposeData[index]['name']
      } else {
        value = value + ';' + purposeData[index]['name']
      }
    }

    this.setData({
      purposeData: purposeData,
      value: value

    })
  },
  // 上一步
  tapGoBack: function () {
    wx.navigateBack()
  },
  // 下一步
  tapLoginDone: function () {
    var objective = this.data.value

    // 验证job是不为空
    if (!objective) {
      util.alertMsg('请选择或者输入您的健身目的！')
      return
    }
    
    // 编辑健身目的
    if (this.data.edit) {
      // 获取前一页数据
      var userInfo = util.getPrevPageData('userInfo')
      userInfo.objective = objective
      // 修改前一页数据
      util.editPrevPageData({
        userInfo: userInfo
      })
      // 设置本页数据
      this.setData({
        objective: objective
      })
      wx.navigateBack()
    } else {
      // 初始化用户资料选择健身目的
      app.updateUserInfo.objective = objective
      // 下载微信头像
      var self = this
      var headImg = app.updateUserInfo.headImg
      if (headImg) {
        wx.downloadFile({
          url: headImg,
          success: function (res) {
            if (res.statusCode === 200) {
              var tempFilePath = res.tempFilePath

              //上传微信头像到自己服务器
              var header = { 'Content-Type': 'multipart/form-data' }
              header.Cookie = 'third_session=' + wx.getStorageSync('SESSION_KEY')
              wx.uploadFile({
                url: smallProgram,
                filePath: tempFilePath,
                name: 'image',
                header: header,
                formData: {
                  path: 'headUrl'
                },
                success: function (res) {
                  if (res.statusCode === 200) {
                    var data = JSON.parse(res.data)
                    if (data.code === 200) {
                      app.updateUserInfo.headImg = data.t.images[0]
                    }
                  }
                },
                fail: function(err){
                  console.log(err)
                },
                complete: function (res) {
                  self.updateUserInfo()
                }
              })
            } else {
              console.log(err)
              self.updateUserInfo()
            }
          },
          fail: function (err) {
            console.log(err)
            self.updateUserInfo()
          }
        })
      } else {
        self.updateUserInfo()
      }
    }
  },
  // 更新用户信息
  updateUserInfo: function () {
    var updateUserInfo = app.updateUserInfo
    var options = {
      url: updateMemInfo,
      data: {
        nickName: updateUserInfo.userName,
        headImg: updateUserInfo.headImg,
        stature: updateUserInfo.height,
        weight: updateUserInfo.weight,
        profession: updateUserInfo.job,
        objective: updateUserInfo.objective,
        birthday: updateUserInfo.birthday + '-1-1',
        gander: updateUserInfo.sex
      },
      success: function(){
        util.alertMsg({
          content: '更新成功！',
          success: function () {
            wx.reLaunch({
              url: '/pages/index/index',
            })
          }
        })
      },
      fail: function(){
        util.alertMsg({
          content: '更新失败！',
          success: function(){
            wx.reLaunch({
              url: '/pages/index/index',
            })
          }
        })
      },
      complete: function(){
        util.hideLoading()
      }
    }
    
    util.XHR(options)
  }
})